import { jAlert3 } from ".";


export const isMiniProgram = async (): Promise<Boolean> => {
  return new Promise((resolve, reject) => {
    if (/MicroMessenger/i.test(navigator.userAgent)) {
      // #ifdef MP-WEIXIN
      wx.miniProgram.getEnv((res) => {
        if (res.miniprogram) {
          resolve(true)
          console.log('内嵌在小程序')
        } else {
          console.log('微信浏览器')
          resolve(false)
        }
      })
      // #endif
      // #ifndef MP-WEIXIN
      resolve(false)
      // #endif
    }
    else {
      console.log('外部浏览器')
      resolve(false)
    }
  })
};




const openExternalBrowser = (url) => {
  // 判断平台：App 端使用 plus.runtime, H5 端使用 window.open
  const platform = uni.getSystemInfoSync().platform
  console.log('打印***platform', platform)
  if (platform === 'android' || platform === 'ios') {
    plus.runtime.openURL(url);
  } else {
    window.open(url, '_blank');
  }
}

// 调用示例
// openExternalBrowser('https://www.example.com/external-page');


// function splitByFirstQuestionMark(url: string): Array<string> {
//   const regex = /^([^?]*)\?(.*)/;
//   const match = url.match(regex);

//   if (match) {
//     return [match[1], match[2]]; // [前半部分, 后半部分]
//   } else {
//     return [url, '']; // 如果没有 ?，返回整个字符串和空字符串
//   }
// }


// function splitByFirstQuestionMark(url: string): Array<string> {
//   const index = url.indexOf('?');
//   if (index === -1) return [url, ''];
//   return [url.slice(0, index), url.slice(index + 1)];
// }


const getQueryVariable = (url: string, variable: string) => {
  url = url.split('?')[1]
  if (url) {
    var vars = url.split('&')
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=')
      if (pair[0] == variable) {
        return pair[1]
      }
    }
  } else {
    return false
  }
}

const launchApp = () => {
  let _this = this;
  // 判断平台
  if (plus.os.name == 'Android') {
    plus.runtime.launchApplication(
      {
        pname: 'com.taobao.taobao'
      },
      function (e) {
        console.log('Open system default browser failed: ' + e.message);
      }
    );
  } else if (plus.os.name == 'iOS') {
    plus.runtime.launchApplication({ action: 'taobao://' }, function (e) {
      console.log('Open system default browser failed: ' + e.message);
    });
  }

}


export const goPagePolymerization = async (url: string) => {

  const type = '1' as '1' | '2'

  if (!url) return
  const appid = getQueryVariable(url, 'appid')
  const ghId = getQueryVariable(url, 'ghId')
  const path = getQueryVariable(url, 'path')
  const isOpenExtenal = getQueryVariable(url, 'isOpenExtenal')
  const isEmbedded = getQueryVariable(url, 'isEmbedded')
  console.log('打印***appid', appid)
  const needLogin = getQueryVariable(url, 'needLogin')
  const urlScheme = getQueryVariable(url, 'urlScheme')
  const pname = getQueryVariable(url, 'pname')

  if (needLogin == 'T') {
    //   if (!user || !user.memberId) {
    //     // 登录完跳转回来
    //     toLogin({
    //       redirect_url: url
    //     })
    //   }
  }

  // #ifdef H5
  const isMini = await isMiniProgram()
  if (isMini) {
    if (url.startsWith('http')) {
      wx.navigateTo({
        url: '/pages/webview/index?url=' + encodeURIComponent(url)
      })
    } else if (url.indexOf('page') > -1) {
      wx.navigateTo({
        url
      })
    }
    return
  }




  if (url.indexOf('http') == 0 || urlScheme) {
    window.location.href = url
  } else if (url.indexOf('pages') != -1) {
    toPage(url)
  }




  // #endif

  //  #ifdef APP-PLUS
  if (url.startsWith('http')) {
    if (isOpenExtenal === 'T') {

      // 跳转浏览器
      plus.runtime.openURL(url, function (res) {
        console.log(res);
      });
    } else {

      uni.navigateTo({
        url: '/pages/webview/index?url=' + encodeURIComponent(url)
      })
    }

  } else if (urlScheme) {
    plus.runtime.openURL(urlScheme, function (res) {
      console.log(res);
    });
  } else if (ghId) {
    // toMiniProgram({ appid, path: url, ghId, isEmbedded })
    plus.share.getServices(function (res) {
      let sweixin = null
      for (let i = 0; i < res.length; i++) {
        const t = res[i]
        if (t.id == 'weixin') {
          sweixin = t
        }
      }
      if (sweixin) {
        sweixin.launchMiniProgram({
          id: ghId,
          type: 0,
          path
        })
      }
    })
  } else if (pname) {
    launchApp()
  } else if (url.indexOf('page') == -1) {
    jAlert3(url)
  } else {
    toPage(url)
  }
  //  #endif

  // #ifndef H5 || APP-PLUS
  if (url.startsWith('http')) {
    uni.navigateTo({
      url: '/pages/webview/index?url=' + encodeURIComponent(url)
    })
  } else if (appid) {
    const params = {
      appId: appid,
      path: url,
    }
    if (isEmbedded === 'T') {
      uni.openEmbeddedMiniProgram(params)
    } else {
      uni.navigateToMiniProgram(params)
    }
  } else if (url.indexOf('page') == -1) {
    jAlert3(url)
  } else {
    toPage(url)
  }
  // #endif
}



const toPage = (url: string) => {
  uni.navigateTo({
    url,
    fail() {
      uni.switchTab({
        url,
      })
    }
  })
}

